package org.ricks.condition1;

import org.ricks.ioc.event.IEvent;

import java.util.List;
import java.util.function.Predicate;

public class CompositeCondition implements Condition {
    private final List<Condition> conditions;
    private final Predicate<List<Condition>> completionPredicate;

    public CompositeCondition(List<Condition> conditions, Predicate<List<Condition>> completionPredicate) {
        this.conditions = List.copyOf(conditions);
        this.completionPredicate = completionPredicate;
    }

    @Override
    public void emit(IEvent event) {
        conditions.stream()
                .filter(c -> !c.isDone())
                .forEach(c -> c.emit(event));
    }

    @Override
    public boolean isDone() {
        return completionPredicate.test(conditions);
    }

    // 预定义常用组合类型
    public static CompositeCondition allOf(List<Condition> conditions) {
        return new CompositeCondition(conditions, cs -> cs.stream().allMatch(Condition::isDone));
    }

    public static CompositeCondition anyOf(List<Condition> conditions) {
        return new CompositeCondition(conditions, cs -> cs.stream().anyMatch(Condition::isDone));
    }
}
